import 'package:flutter/material.dart';

class FloatingWindowPage extends StatelessWidget {
  const FloatingWindowPage({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('全屏悬浮框')),
        body: Center(
          child: ElevatedButton(
            onPressed: () {
              // 在按钮点击时显示悬浮框
              showFloatingWindow(context);
            },
            child: Text('显示悬浮框'),
          ),
        ),
      ),
    );
  }

  // 显示全屏悬浮框
  void showFloatingWindow(BuildContext context) {
    final overlay = Overlay.of(context);

    // 创建一个OverlayEntry
    final overlayEntry = OverlayEntry(
      builder: (context) => const FloatingWindow(),
    );

    // 插入到Overlay中
    overlay.insert(overlayEntry);

    // 关闭悬浮框
    // Future.delayed(const Duration(seconds: 5), () {
    //   overlayEntry.remove();
    // });
  }
}

class FloatingWindow extends StatefulWidget {
  const FloatingWindow({super.key});

  @override
  _FloatingWindowState createState() => _FloatingWindowState();
}

class _FloatingWindowState extends State<FloatingWindow> {
  double left = 100;
  double top = 100;
  double startX = 0;
  double startY = 0;

  @override
  Widget build(BuildContext context) {
    return Positioned(
      left: left,
      top: top,
      child: GestureDetector(
        onPanStart: (details) {
          startX = details.globalPosition.dx;
          startY = details.globalPosition.dy;
        },
        onPanUpdate: (details) {
          setState(() {
            // 计算拖动的偏移量
            left += details.globalPosition.dx - startX;
            top += details.globalPosition.dy - startY;

            // 更新起始位置
            startX = details.globalPosition.dx;
            startY = details.globalPosition.dy;
          });
        },
        child: Material(
          elevation: 8,
          borderRadius: BorderRadius.circular(10),
          child: Container(
            width: 200,
            height: 200,
            color: Colors.blueAccent,
            child: Center(
              child: Text(
                '拖动我！',
                style: TextStyle(color: Colors.white, fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
